package org.jfk.sys.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jfk.core.controller.BaseController;
import org.jfk.sys.security.Urls;

import com.jfinal.plugin.activerecord.Record;

public class UrlController extends BaseController {
	private static Logger logger = Logger.getLogger(UrlController.class);  

	public void ajaxGetAllUrlsByUser(){
		int userId = this.getParaToInt();
		List<Record> allUrls = Urls.dao.getAllUrls();
		
		List<Record> rightUrls = Urls.dao.getRightUrlsByUser(userId);
		
		List<Map> mixUrls = new ArrayList();
		List module = new ArrayList();
		List checkedUrl = new ArrayList();
		
		for (int i = 0 ; i < rightUrls.size() ; i++){
			String url_id = rightUrls.get(i).get("url_id").toString();
			checkedUrl.add(url_id);
		}
		
		for (int i = 0 ; i < allUrls.size() ; i++){
			String id = allUrls.get(i).get("id").toString();
			String pid = allUrls.get(i).get("pid").toString();
			String url_name = allUrls.get(i).get("url_name");
			String module_name = allUrls.get(i).get("module_name");
			if (!module.contains(pid)){
				module.add(pid);
				Map m = new HashMap();
				m.put("id", pid);
				m.put("pId", "0");
				m.put("name", module_name);
				m.put("open", "true");
				m.put("checked", "true");
				mixUrls.add(m);
			}
			Map m = new HashMap();
			m.put("id", id);
			m.put("pId", pid);
			m.put("name", url_name);
			m.put("open", "true");
			
			if (checkedUrl.contains(id)){
				m.put("checked", "true");
			}
			mixUrls.add(m);
		}
		
		super.renderJson(mixUrls);
	}

	
	public void ajaxGetAllUrlsByRole(){
		int roleId = this.getParaToInt(0,-1);
		List<Record> allUrls = Urls.dao.getAllUrls();
		
		List<Record> rightUrls = Urls.dao.getRightUrlsByRole(roleId);
		
		List<Map> mixUrls = new ArrayList();
		List module = new ArrayList();
		List checkedUrl = new ArrayList();
		
		for (int i = 0 ; i < rightUrls.size() ; i++){
			String url_id = rightUrls.get(i).get("urlId").toString();
			checkedUrl.add(url_id);
		}
		
		for (int i = 0 ; i < allUrls.size() ; i++){
			String id = allUrls.get(i).get("id").toString();
			String pid = allUrls.get(i).get("pid").toString();
			String url_name = allUrls.get(i).get("url_name");
			String module_name = allUrls.get(i).get("module_name");
//			if (!module.contains(pid)){
//				module.add(pid);
//				Map m = new HashMap();
//				m.put("id", pid);
//				m.put("pId", "0");
//				m.put("name", module_name);
//				m.put("open", "true");
//				mixUrls.add(m);
//			}
			Map m = new HashMap();
			m.put("id", id);
			m.put("pId", pid);
			m.put("name", url_name);
			m.put("open", "true");
			
			if (checkedUrl.contains(id)){
				m.put("checked", "true");
			}
			mixUrls.add(m);
		}
		
		super.renderJson(mixUrls);
	}	
}
